package com.hengxinguotong.hxgtwygsp.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.hengxinguotong.hxgtwygsp.model.DownloadInfo;

import java.util.ArrayList;
import java.util.List;


public class DownloadDAO
{
    private SQLiteDatabase sqLiteDatabase;

    public DownloadDAO(Context context)
    {
        sqLiteDatabase = MyOpenHelper.getInstance(context);
    }

    /**
     * 查看数据库中是否有数据
     *
     * @param urlstr
     * @return boolean
     * @author hjz
     * @since 2018/12/25 18:46
     */
    public boolean isHasInfors(String urlstr)
    {
        String sql = "select count(*) from download_info where url=?";
        Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{urlstr});
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        cursor.close();
        return count == 0;
    }

    /**
     * 保存 下载的具体信息
     *
     * @param infos
     */
    public void saveInfos(List<DownloadInfo> infos)
    {
        for (DownloadInfo info : infos)
        {
            String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url) values (?,?,?,?,?)";
            Object[] bindArgs = {info.getThreadId(), info.getStartPos(),
                    info.getEndPos(), info.getCompeleteSize(), info.getUrl()};
            sqLiteDatabase.execSQL(sql, bindArgs);
        }
    }

    /**
     * 得到下载具体信息
     *
     * @param urlstr
     * @return
     */
    public List<DownloadInfo> getInfos(String urlstr)
    {
        List<DownloadInfo> list = new ArrayList<DownloadInfo>();
        String sql = "select * from download_info where url=?";
        Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{urlstr});
        while (cursor.moveToNext())
        {
            DownloadInfo info = new DownloadInfo(urlstr);
            info.setThreadId(cursor.getInt(cursor.getColumnIndex("thread_id")));
            info.setStartPos(cursor.getLong(cursor.getColumnIndex("start_pos")));
            info.setEndPos(cursor.getLong(cursor.getColumnIndex("end_pos")));
            info.setCompeleteSize(cursor.getLong(cursor.getColumnIndex("compelete_size")));
            list.add(info);
        }
        cursor.close();
        return list;
    }

    /**
     * 更新数据库中的下载信息
     *
     * @param threadId
     * @param compeleteSize
     * @param urlstr
     */
    public void updataInfos(int threadId, long compeleteSize, String urlstr)
    {
        String sql = "update download_info set compelete_size=? where thread_id=? and url=?";
        Object[] bindArgs = {compeleteSize, threadId, urlstr};
        sqLiteDatabase.execSQL(sql, bindArgs);
    }

    /**
     * 下载完成后删除数据库中的数据
     *
     * @param url
     */
    public void delete(String url)
    {
        sqLiteDatabase.delete("download_info", "url=?", new String[]{url});
    }
}
